#pragma once
namespace key_value
{
	template<class K, class V>
	struct BSTreeNode
	{
		typedef BSTreeNode<K, V> Node;
		Node* _left;
		Node* _right;
		K _key;
		V _value;
		BSTreeNode(const K& key, const V& value)
			:_left(nullptr)
			,_right(nullptr)
			,_key(key)
			,_value(value)
		{
		}

	};
	template<class K,class V>
	class BSTree
	{
		typedef BSTreeNode<K, V> Node;

	public:
		bool Insert(const K& key, const V& value)
		{
			if (_root == nullptr)
			{
				_root = new Node(key, value);
				return true;
			}
			Node* prev = nullptr;
			Node* cur = _root;
			while (cur)
			{
				if (cur->_key > key)
				{
					prev = cur;
					cur = cur->_left;
				}
				else if (cur->_key < key)
				{
					prev = cur;
					cur = cur->_right;
				}
				else
				{
					return false;
				}
			}

			Node* newnode = new Node(key,value);
			if (prev->_key > key)
			{
				prev->_left = newnode;
			}
			else if (prev->_key < key)
			{
				prev->_right = newnode;
			}
			
			return true;

		}

		Node* Find(const K& key)
		{
			Node* cur = _root;
			while (cur)
			{
				if (cur->_key > key)
				{
					cur = cur->_left;
				}
				else if (cur->_key < key)
				{
					cur = cur->_right;
				}
				else
				{
					return cur;
				}
			}
		}

		bool Erase(const K& key)
		{
			Node* prev = nullptr;
			Node* cur = _root;
			while (cur)
			{
				if (cur->_key > key)
				{
					prev = cur;
					cur = cur->_left;
				}
				else if(cur->_key<key)
				{
					prev = cur;
					cur = cur->_right;
				}
				else
				{
					if (cur->_left == nullptr)
					{
						if (cur == _root)
						{
							cur = cur->_right;
						}
						else 
						{
							if (cur == prev->_left)
							{
								prev->_left = cur->_right;
							}
							else
							{
								prev->_right = cur->_right;
							}
						}
						delete cur;
						return true;
					}
					else if (cur->_right == nullptr)
					{
						if (cur == _root)
						{
							cur = cur->_left;
						}
						else
						{
							if (cur == prev->_left)
							{
								prev->_left = cur->_left;
							}
							else
							{
								prev->_right = cur->_left;
							}
						}
						delete cur;
						return true;
					}
					else
					{
						Node* RightMinParent = cur;
						Node* RightMin = cur->_right;
						while (RightMin->_left)
						{
							RightMinParent = RightMin;
							RightMin = RightMin->_left;
						}
						cur->_key = RightMin->_key;
						if (RightMin == RightMinParent->_left)
						{
							RightMinParent->_left = RightMin->_right;
						}
						else
						{
							RightMinParent->_right = RightMin->_right;
						}

						delete RightMin;
						return true;
					}
				}
			}
			return false;
		}
		void Inoder()
		{
			inoderprint(_root);
			cout << endl;
		}
		void inoderprint( Node* root)
		{
			if (root == nullptr)
			{
				return;
			}
			inoderprint(root->_left);
			cout << root->_key << " " << root->_value << endl;
			inoderprint(root->_right);
		}
	private:
		Node* _root = nullptr;
	};



}
